package com.primeton.eos.oss.model.controller;

import java.io.*;
import java.util.ArrayList;
import java.util.List;
import java.util.zip.ZipEntry;
import java.util.zip.ZipOutputStream;

import cn.hutool.core.collection.CollectionUtil;
import cn.hutool.core.util.StrUtil;
import com.eos.spring.dao.CriteriaBuilder;
import com.primeton.eos.oss.model.dao.ProjectFileDao;
import com.primeton.eos.oss.model.newdataset.ProjectFile;
import com.primeton.eos.oss.model.result.BusinessException;
import com.primeton.eos.oss.model.result.ErrorResult;
import com.primeton.eos.oss.model.result.RetCode;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;

import com.primeton.eos.oss.model.result.SuccessResult;
import com.primeton.eos.oss.model.service.FileService;

import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;

import javax.servlet.http.HttpServletResponse;

@Api(tags = "对外服务管理")
@RestController
@RequestMapping("/api/out/")
public class OutBoundController {
	private static final Logger log = LoggerFactory.getLogger(OutBoundController.class);

	@Autowired
	ProjectFileDao projectFileDao;


	@Autowired
	FileService fileService;
	
	@ApiOperation("接受文件流数据")
    @GetMapping("/loadWrite")
	public String loadWrite(@RequestParam("fileZips") MultipartFile file) throws IOException {
		   try (InputStream inputStream = file.getInputStream()) {
			fileService.loadWrite(inputStream);
		} catch (Exception ex) {
			log.info("OutBoundController.loadWrite is error:"+ex);
		}
		return new SuccessResult().toJSONString();
	}


	@ApiOperation("通过项目ID读取项目附件")
	@GetMapping("/readFile")
	public String readFile(HttpServletResponse response,String projectid) throws IOException {
		if (StrUtil.isBlank(projectid)){
			return new ErrorResult(RetCode.FAILE,"项目ID不能为空").toJSONString();
		}
		// 通过项目ID获取其附件信息
		CriteriaBuilder cb = new CriteriaBuilder(ProjectFile.QNAME);
		cb.and("projectid", projectid);
		cb.and("del_flag", "N");
		List<ProjectFile> datas = projectFileDao.queryEntitiesByCriteria(cb.build());
		if (CollectionUtil.isEmpty(datas)){
			return new ErrorResult(RetCode.FAILE,"此项目暂无查询到附件信息").toJSONString();
		}
		// 取其中一条的相对路径 存放规则filePath+项目ID+附件
		ProjectFile projectFile=datas.get(0);
		String path=projectFile.getFilePath()+"/file/"+projectid+"/";
		// 所有附件的绝对路径
		List<String> files=new ArrayList<>();
		for (String str:projectFile.getFileNames().split(";")){
			files.add(path+str);
		}
		// 将files进行ZIP压缩 然后名称打包成  projectFile.getProjectid().zip格式进行输出
		// ZIP文件的名称
		String zipFileName = projectFile.getProjectid() + ".zip";
		response.setContentType("application/zip");
		response.setHeader("Content-Disposition", "attachment; filename=\"" + zipFileName + "\"");
		try (ZipOutputStream zipOutputStream = new ZipOutputStream(response.getOutputStream())) {
			for (String filePath : files) {
				File file = new File(filePath);
				if (file.exists()) {
					zipOutputStream.putNextEntry(new ZipEntry(file.getName()));

					// 将文件内容写入 ZIP
					try (FileInputStream fileInputStream = new FileInputStream(file)) {
						byte[] buffer = new byte[1024];
						int length;
						while ((length = fileInputStream.read(buffer)) > 0) {
							zipOutputStream.write(buffer, 0, length);
						}
					}
					zipOutputStream.closeEntry();
				}
			}
		} catch (IOException e) {
			response.setStatus(HttpServletResponse.SC_INTERNAL_SERVER_ERROR);
			response.getWriter().write("ZIP 文件创建时发生错误: " + e.getMessage());
		}

		return new SuccessResult().toJSONString();
	}

}
